<template>
  <div class="coffee-wall">
    <!-- 背景装饰 -->
    <div class="wall-background"></div>

    <!-- 咖啡墙标题 -->
    <div class="wall-header">
      <p class="wall-subtitle">每一杯咖啡都代表着一份支持与温暖</p>

      <!-- 管理员功能按钮 -->
      <div v-if="hasAdminPermission" class="admin-controls">
        <a-button type="primary" :ghost="!adminMode" @click="toggleAdminMode" class="admin-toggle-btn">
          {{ adminMode ? '退出管理' : '进入管理' }}
        </a-button>
        <a-button v-if="adminMode" type="primary" @click="openAddSupporter" class="admin-add-btn">
          <template #icon><plus-outlined /></template>
          添加支持者
        </a-button>
      </div>
    </div>

    <!-- 咖啡杯网格容器 -->
    <div class="coffee-grid" :style="{ backgroundSize }">
      <div
        v-for="(cup, index) in coffeeData"
        :key="index"
        class="coffee-cup"
        :class="{
          'has-avatar': cup.hasAvatar,
          'is-empty': !cup.hasAvatar,
          'is-hovered': hoveredIndex === index
        }"
        @click="handleCupClick(cup)"
        @mouseenter="showCupTip($event, cup, index)"
        @mousemove="moveCupTip($event)"
        @mouseleave="hideCupTip()"
      >
        <!-- 咖啡杯背景 + 自定义tip -->
        <div class="cup-background" :style="{ backgroundImage: getCupBackground(cup, index) }">
          <!-- 头像显示 -->
          <div v-if="cup.hasAvatar" class="avatar-container">
            <img :src="getImageUrl(cup.avatar)" :alt="cup.name || 'avatar'" class="avatar" />
          </div>

          <!-- 空座位提示 -->
          <div v-else class="empty-seat-hint">
            <div class="plus-icon">+</div>
            <div class="hint-text">点击支持</div>
          </div>

          <!-- 管理模式下的操作按钮 -->
          <div v-if="adminMode && hasAdminPermission && cup.hasAvatar" class="admin-actions" @click.stop="">
            <a-button type="primary" size="small" @click="openEditSupporter(cup)" class="action-btn edit-btn">
              <template #icon><edit-outlined /></template>
            </a-button>
            <a-popconfirm title="确定删除这个支持者吗？" @confirm="deleteSupporterHandler(cup)" ok-text="确定" cancel-text="取消">
              <a-button type="primary" danger size="small" class="action-btn delete-btn">
                <template #icon><delete-outlined /></template>
              </a-button>
            </a-popconfirm>
          </div>
        </div>
      </div>
      <!-- 自定义tip -->
      <div v-if="cupTip.visible" class="cup-tip" :style="cupTip.style">{{ cupTip.text }}</div>
    </div>

    <!-- 弹窗组件 -->
    <a-modal v-model:open="modalVisible" :title="null" width="500px" :footer="null" centered class="certificate-modal">
      <div class="certificate-container">
        <!-- 花边背景 -->
        <div class="flower-border-bg"></div>

        <!-- 证书内容 -->
        <div class="certificate-content">
          <!-- 标题 -->
          <div class="certificate-header">
            <h2 class="certificate-title">{{ modalData.name }}</h2>
            <p class="certificate-subtitle">开源贡献荣誉证书</p>
          </div>

          <!-- 咖啡杯图标 -->
          <div class="certificate-cup">
            <div class="cup-image">
              <!-- 咖啡杯图片 -->
              <img :src="getCoffeeCupImageUrl(modalData)" alt="coffee cup" class="cup-img" />
              <!-- 头像显示 -->
              <img :src="getCertAvatarUrl(modalData.avatar)" :alt="modalData.name || 'avatar'" class="cert-avatar" />
            </div>
            <div class="cup-badge">x{{ modalData.count.toString().replace('杯', '') }}</div>
          </div>

          <!-- 支持者名称 -->
          <div class="supporter-name">{{ modalData.name }}</div>

          <!-- 证书信息 -->
          <div class="certificate-info">
            <p class="support-message">{{ modalData.message }}</p>
            <p class="support-date">—— {{ modalData.time }} ——</p>
          </div>
        </div>

        <!-- 底部按钮 -->
        <div class="certificate-actions">
          <a-button class="cert-btn cert-btn-download" @click="downloadCertificate">下载证书</a-button>
          <a-button type="primary" class="cert-btn cert-btn-support" @click="goToSponsor">前往赞助</a-button>
        </div>
      </div>
    </a-modal>

    <!-- 编辑支持者弹窗 -->
    <a-modal v-model:open="editModalVisible" :title="isEditMode ? '编辑支持者' : '添加支持者'" width="500px" centered class="edit-supporter-modal">
      <div class="edit-form">
        <div class="form-item">
          <label class="form-label">支持者姓名 <span class="required">*</span></label>
          <a-input v-model:value="editForm.name" placeholder="请输入支持者姓名" class="form-input" />
        </div>

        <div class="form-item">
          <label class="form-label">支持杯数 <span class="required">*</span></label>
          <a-input-number v-model:value="editForm.count" placeholder="请输入支持杯数" :min="1" class="form-input" />
        </div>
        <div class="form-item">
          <label class="form-label">上传头像</label>
          <a-upload v-model:file-list="avatarFileList" name="avatar" list-type="picture-card" class="avatar-uploader" :show-upload-list="false" :before-upload="beforeAvatarUpload" :custom-request="customAvatarUpload" @change="handleAvatarChange">
            <div v-if="editForm.avatar" class="avatar-preview">
              <img :src="getImageUrl(editForm.avatar)" alt="avatar" />
              <div class="avatar-overlay">
                <div class="avatar-actions">
                  <a-button type="text" size="small" @click.stop="handleAvatarRemove" class="remove-btn">删除</a-button>
                </div>
              </div>
            </div>
            <div v-else class="upload-placeholder">
              <loading-outlined v-if="avatarUploading" />
              <plus-outlined v-else />
              <div class="upload-text">{{ avatarUploading ? '上传中' : '上传头像' }}</div>
            </div>
          </a-upload>
        </div>

        <div class="form-item">
          <label class="form-label">咖啡杯类型 <span class="required">*</span></label>
          <div class="coffee-type-selector">
            <div class="coffee-option" :class="{ active: editForm.typeIndex === 0 }" @click="selectCoffeeType(0)">
              <img :src="coffee10StoryUrl" alt="粉色咖啡" class="coffee-preview" />
              <span class="coffee-label">粉色咖啡</span>
            </div>
            <div class="coffee-option" :class="{ active: editForm.typeIndex === 1 }" @click="selectCoffeeType(1)">
              <img :src="coffee100StoryUrl" alt="青色咖啡" class="coffee-preview" />
              <span class="coffee-label">青色咖啡</span>
            </div>
            <div class="coffee-option" :class="{ active: editForm.typeIndex === 2 }" @click="selectCoffeeType(2)">
              <img :src="coffee1000StoryUrl" alt="紫色咖啡" class="coffee-preview" />
              <span class="coffee-label">紫色咖啡</span>
            </div>
          </div>
        </div>

        <div class="form-item">
          <label class="form-label">支持留言</label>
          <a-textarea v-model:value="editForm.message" placeholder="请输入支持留言（可选）" :rows="3" class="form-input" />
        </div>
      </div>

      <template #footer>
        <a-button @click="cancelEdit">取消</a-button>
        <a-button type="primary" @click="saveSupporter">{{ isEditMode ? '更新' : '添加' }}</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, onUnmounted, nextTick, watch } from 'vue'
import { useRouter } from 'vue-router'
import { CoffeeOutlined, EditOutlined, DeleteOutlined, PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import html2canvas from 'html2canvas'
import { useUserStore } from '@/stores/user'
import { getSupporters, addSupporter, updateSupporter, deleteSupporter, uploadImg } from '@/utils/api'
import { Tooltip as ATooltip } from 'ant-design-vue'

// 导入图片资源
import logoUrl from '@/assets/logo.png'

import coffee10StoryUrl from '@/assets/coffee-10-story.svg'
import coffee100StoryUrl from '@/assets/coffee-100-story.svg'
import coffee1000StoryUrl from '@/assets/coffee-1000-story.svg'
import coffee10HoverUrl from '@/assets/coffee-10-hover.svg'
import coffee100HoverUrl from '@/assets/coffee-100-hover.svg'
import coffee1000HoverUrl from '@/assets/coffee-1000-hover.svg'
import coffee10SeatUrl from '@/assets/coffee-10-seat-hover.svg'
import coffee100SeatUrl from '@/assets/coffee-100-seat-hover.svg'
import coffee1000SeatUrl from '@/assets/coffee-1000-seat-hover.svg'

const router = useRouter()
const userStore = useUserStore()

// 访问权限控制
const ALLOWED_USERNAME = 'woaichitudouo'

/**
 * 检查用户是否有管理权限
 * 只有登录且用户名为指定账号的用户才能管理
 */
const hasAdminPermission = computed(() => {
  return userStore.isAuthenticated && userStore.username === ALLOWED_USERNAME
})

// 响应式数据
const modalVisible = ref(false)
const hoveredIndex = ref(-1)
const backgroundSize = ref('100% 140px') // 动态背景尺寸

// 管理功能相关状态
const adminMode = ref(false) // 是否处于管理模式
const editModalVisible = ref(false) // 编辑弹窗显示状态
const isEditMode = ref(false) // 是否为编辑模式（false为添加模式）
const editingSupporter = ref(null) // 正在编辑的支持者

// 弹窗数据
const modalData = reactive({
  title: '',
  name: '',
  count: '',
  type: '',
  typeIndex: 0,
  time: '',
  message: '',
  avatar: ''
})

// 编辑表单数据
const editForm = reactive({
  count: 10,
  typeIndex: 0,
  hasAvatar: true,
  name: '',
  avatar: '',
  message: ''
})

// 头像上传相关状态
const avatarUploading = ref(false)
const avatarFileList = ref([])

// 咖啡杯数据
const coffeeData = ref([])

// 统计信息
const totalSupporters = computed(() => {
  return coffeeData.value.filter((cup) => cup.hasAvatar).length
})

// 自定义tip状态
const cupTip = reactive({
  visible: false,
  text: '',
  style: {
    position: 'fixed',
    left: '0px',
    top: '0px',
    zIndex: 9999,
    pointerEvents: 'none'
  }
})

// 从API获取咖啡墙数据
const loadCoffeeData = async () => {
  try {
    // 获取支持者数据
    const response = await getSupporters({ limit: 100 })
    if (response.code === 200) {
      const supporters = response.data.supporters || []

      // 添加空座位数据以填充到至少30个位置
      const emptySeatsData = []
      const totalSlots = Math.max(999, supporters.length + 10) // 至少30个位置，或者支持者数量+10

      for (let i = supporters.length; i < totalSlots; i++) {
        const typeIndex = i % 3 // 循环使用不同类型
        const types = ['10杯', '100杯', '1000杯']
        const counts = [10, 100, 1000]

        emptySeatsData.push({
          id: `empty_${i}`,
          count: counts[typeIndex],
          type: types[typeIndex],
          typeIndex,
          hasAvatar: false,
          name: '',
          avatar: '',
          time: '',
          message: ''
        })
      }

      // 合并数据：支持者在前，空座位在后
      coffeeData.value = [...supporters, ...emptySeatsData]
    } else {
      message.error('获取支持者数据失败')
      // 降级到初始化空数据
      initEmptyData()
    }
  } catch (error) {
    message.error('获取支持者数据失败')
    // 降级到初始化空数据
    initEmptyData()
  }
}

// 初始化空数据（作为降级方案）
const initEmptyData = () => {
  const emptySeatsData = []
  for (let i = 0; i < 30; i++) {
    const typeIndex = i % 3 // 循环使用不同类型
    const types = ['10杯', '100杯', '1000杯']
    const counts = [10, 100, 1000]

    emptySeatsData.push({
      id: `empty_${i}`,
      count: counts[typeIndex],
      type: types[typeIndex],
      typeIndex,
      hasAvatar: false,
      name: '',
      avatar: '',
      time: '',
      message: ''
    })
  }

  coffeeData.value = emptySeatsData
}

// 获取咖啡杯背景图片
const getCupBackground = (cup, index) => {
  const { typeIndex, hasAvatar } = cup
  const isCurrentHovered = hoveredIndex.value === index

  // 根据类型选择对应的图片
  const storyImages = [coffee10StoryUrl, coffee100StoryUrl, coffee1000StoryUrl]
  const hoverImages = [coffee10HoverUrl, coffee100HoverUrl, coffee1000HoverUrl]
  const seatImages = [coffee10SeatUrl, coffee100SeatUrl, coffee1000SeatUrl]

  let imageUrl

  if (!hasAvatar) {
    // 没有头像，显示空座位
    imageUrl = seatImages[typeIndex]
  } else if (isCurrentHovered) {
    // 有头像且鼠标悬停，显示悬停效果
    imageUrl = hoverImages[typeIndex]
  } else {
    // 有头像的普通状态
    imageUrl = storyImages[typeIndex]
  }

  return `url(${imageUrl})`
}

// 获取弹窗中的咖啡杯图像URL
const getCoffeeCupImageUrl = (modalData) => {
  const storyImages = [coffee10StoryUrl, coffee100StoryUrl, coffee1000StoryUrl]
  const imageUrl = storyImages[modalData.typeIndex] || storyImages[0]
  return imageUrl
}

const getImageUrl = (filename) => {
  // 如果没有文件名，返回默认logo
  if (!filename) {
    return logoUrl
  }

  // 如果已经是完整URL，直接返回
  if (filename.startsWith('http://') || filename.startsWith('https://')) {
    return filename
  }

  // 构建静态资源的完整路径
  return `${import.meta.env.VITE_APP_API_BASE_URL}/assets/uploads/${filename}`
}

// 获取证书弹窗中的头像URL
const getCertAvatarUrl = (avatar) => {
  // 如果没有头像，返回默认logo
  if (!avatar) {
    return logoUrl
  }

  // 如果是base64格式，直接返回
  if (avatar.startsWith('data:image/')) {
    return avatar
  }

  // 如果是完整URL，直接返回
  if (avatar.startsWith('http://') || avatar.startsWith('https://')) {
    return avatar
  }

  // 否则使用getImageUrl处理
  return getImageUrl(avatar)
}

// 处理鼠标进入
const handleMouseEnter = (cup, index) => {
  hoveredIndex.value = index
}

// 处理鼠标离开
const handleMouseLeave = (cup, index) => {
  hoveredIndex.value = -1
}

// 工具函数：将图片 URL 转为 base64
function toBase64(url) {
  return new Promise((resolve, reject) => {
    const img = new window.Image()
    img.crossOrigin = 'Anonymous'
    img.onload = function () {
      const canvas = document.createElement('canvas')
      canvas.width = img.width
      canvas.height = img.height
      const ctx = canvas.getContext('2d')
      ctx.drawImage(img, 0, 0)
      resolve(canvas.toDataURL('image/png'))
    }
    img.onerror = reject
    img.src = url
  })
}

// 处理咖啡杯点击
const handleCupClick = async (cup) => {
  if (cup.hasAvatar) {
    modalData.title = `${cup.type}支持者`
    modalData.name = cup.name
    modalData.count = `${cup.count}杯`
    modalData.type = cup.type
    modalData.typeIndex = cup.typeIndex // 添加 typeIndex
    modalData.time = cup.time
    modalData.message = cup.message
    // 设置头像，直接使用文件名
    if (cup.avatar) {
      try {
        // 构建完整URL然后转为base64
        const fullUrl = getImageUrl(cup.avatar)
        modalData.avatar = await toBase64(fullUrl)
      } catch {
        modalData.avatar = cup.avatar
      }
    } else {
      modalData.avatar = ''
    }
    modalVisible.value = true
  } else {
    // 没有头像的杯子，跳转到赞助页面
    goToSponsor()
  }
}

// 跳转到赞助页面
const goToSponsor = () => {
  window.open('/sponsor', '_blank')
}

// 下载证书功能
const downloadCertificate = async () => {
  try {
    // 获取模态框的 body 元素
    const modalBody = document.querySelector('.ant-modal-body')
    if (!modalBody) {
      console.error('未找到模态框元素')
      return
    }

    // 使用 html2canvas 将元素转换为图片
    const canvas = await html2canvas(modalBody, {
      useCORS: true,
      allowTaint: true,
      backgroundColor: null, // 透明背景
      scale: 2, // 提高清晰度
      logging: false,
      ignoreElements: (element) => {
        // 忽略按钮区域，不包含在截图中
        return element.classList.contains('certificate-actions')
      }
    })

    // 创建下载链接
    const link = document.createElement('a')
    link.download = `${modalData.name}_咖啡证书_${new Date().toISOString().split('T')[0]}.png`
    link.href = canvas.toDataURL('image/png')

    // 触发下载
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)

    console.log('证书下载成功')
  } catch (error) {
    console.error('下载证书失败:', error)
  }
}

// 计算背景尺寸
const calculateBackgroundSize = () => {
  nextTick(() => {
    const coffeeGrid = document.querySelector('.coffee-grid')
    const coffeeCup = document.querySelector('.coffee-cup')

    if (coffeeGrid && coffeeCup) {
      const cupStyle = window.getComputedStyle(coffeeCup)
      const cupHeight = parseFloat(cupStyle.height)
      const gridStyle = window.getComputedStyle(coffeeGrid)
      const gap = parseFloat(gridStyle.gap) || 20

      // 计算实际的行高：杯子高度 + gap
      const actualRowHeight = cupHeight + gap
      backgroundSize.value = `100% ${actualRowHeight}px`

      // 关键修正：横线应该从第一行的杯子底部开始，然后每隔 actualRowHeight 重复
      // 横线位置应该是杯子的实际底部（杯子高度 - 一点偏移让线可见）
      const linePosition = cupHeight - 10 // 横线在杯子底部稍微上方一点

      // 设置背景属性 - 关键是从0开始定位
      coffeeGrid.style.backgroundSize = backgroundSize.value
      coffeeGrid.style.backgroundPositionY = `${linePosition}px`
      coffeeGrid.style.backgroundPosition = `center ${linePosition * 1.63}px`

      // 设置CSS变量
      coffeeGrid.style.setProperty('--row-height', `${actualRowHeight}px`)
      coffeeGrid.style.setProperty('--cup-height', `${cupHeight}px`)
    }
  })
}

// 窗口大小变化监听
const handleResize = () => {
  calculateBackgroundSize()
}

// 监听用户登录状态变化，进行权限检查
watch(
  () => userStore.isAuthenticated,
  (newAuth) => {
    if (newAuth && userStore.username === ALLOWED_USERNAME) {
      // 用户登录且是指定账号，显示管理功能提示
      //   message.success('欢迎管理员，您可以使用管理功能')
    }
  },
  { immediate: true }
)

// 监听用户名变化
watch(
  () => userStore.username,
  (newUsername) => {
    if (userStore.isAuthenticated && newUsername === ALLOWED_USERNAME) {
      //   message.success('欢迎管理员，您可以使用管理功能')
    }
  }
)

// 监听权限变化，当获得权限时初始化管理功能
watch(hasAdminPermission, (newPermission) => {
  if (newPermission) {
    // 获得管理权限时的额外初始化
    nextTick(() => {
      //   console.log('管理权限已获得，可以使用管理功能')
    })
  }
})

// 添加和移除事件监听器
onMounted(() => {
  window.addEventListener('resize', handleResize)
  initData() // 初始化数据并计算背景尺寸
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})

// 初始化数据，合并到上面的 onMounted 中
const initData = async () => {
  await loadCoffeeData()
  // 数据初始化后重新计算背景尺寸
  nextTick(() => {
    calculateBackgroundSize()
  })
}

// ============== 管理功能相关函数 ==============

/**
 * 切换管理模式
 */
const toggleAdminMode = () => {
  adminMode.value = !adminMode.value
  if (adminMode.value) {
    message.success('已进入管理模式')
  } else {
    message.info('已退出管理模式')
  }
}

/**
 * 打开添加支持者弹窗
 */
const openAddSupporter = () => {
  isEditMode.value = false
  editingSupporter.value = null

  // 重置表单
  Object.assign(editForm, {
    count: 1,
    typeIndex: 0,
    hasAvatar: true,
    name: '',
    avatar: '',
    message: ''
  })

  // 重置头像上传
  avatarFileList.value = []
  avatarUploading.value = false

  editModalVisible.value = true
}

/**
 * 打开编辑支持者弹窗
 */
const openEditSupporter = (supporter) => {
  isEditMode.value = true
  editingSupporter.value = supporter

  // 填充表单数据
  Object.assign(editForm, {
    count: supporter.count,
    typeIndex: supporter.typeIndex,
    hasAvatar: supporter.hasAvatar,
    name: supporter.name,
    avatar: supporter.avatar || '',
    message: supporter.message || ''
  })

  // 设置头像上传状态
  if (supporter.avatar) {
    avatarFileList.value = [
      {
        uid: '-1',
        name: 'avatar.png',
        status: 'done',
        url: getImageUrl(supporter.avatar)
      }
    ]
  } else {
    avatarFileList.value = []
  }
  avatarUploading.value = false

  editModalVisible.value = true
}

/**
 * 删除支持者
 */
const deleteSupporterHandler = async (supporter) => {
  try {
    const response = await deleteSupporter(supporter.id)
    if (response.code === 200) {
      message.success('删除成功')
      // 重新加载数据
      await initData()
    } else {
      message.error(response.msg || '删除失败')
    }
  } catch (error) {
    console.error('删除支持者失败:', error)
    message.error('删除失败')
  }
}

/**
 * 保存支持者（添加或编辑）
 */
const saveSupporter = async () => {
  // 表单验证
  if (!editForm.name || !editForm.count || editForm.typeIndex === undefined) {
    message.error('请填写支持者姓名、支持杯数并选择咖啡杯类型')
    return
  }

  // hasAvatar固定为true
  editForm.hasAvatar = true

  // 自动添加当前时间
  const currentTime = new Date().toISOString().split('T')[0]

  try {
    let response
    if (isEditMode.value) {
      // 编辑模式
      response = await updateSupporter(editingSupporter.value.id, {
        ...editForm,
        time: currentTime
      })
    } else {
      // 添加模式
      response = await addSupporter({
        ...editForm,
        time: currentTime
      })
    }

    if (response.code === 200) {
      message.success(isEditMode.value ? '更新成功' : '添加成功')
      editModalVisible.value = false
      // 重新加载数据
      await initData()
    } else {
      message.error(response.msg || '保存失败')
    }
  } catch (error) {
    console.error('保存支持者失败:', error)
    message.error('保存失败')
  }
}

/**
 * 取消编辑
 */
const cancelEdit = () => {
  editModalVisible.value = false
  editingSupporter.value = null
  avatarFileList.value = []
  avatarUploading.value = false
}

// ============== 头像上传功能 ==============

/**
 * 头像上传前的检查
 */
const beforeAvatarUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/webp'
  if (!isJpgOrPng) {
    message.error('只能上传 JPG/PNG/WEBP 格式的图片!')
    return false
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

/**
 * 自定义头像上传
 */
const customAvatarUpload = async ({ file, onSuccess, onError, onProgress }) => {
  try {
    avatarUploading.value = true

    // 创建FormData
    const formData = new FormData()
    formData.append('file', file)

    // 上传图片
    const response = await uploadImg(formData)

    if (response.code === 200) {
      // 直接使用上传接口返回的filename
      editForm.avatar = response.data.filename

      // 调用成功回调
      onSuccess(response, file)

      message.success('头像上传成功')
    } else {
      onError(new Error(response.msg || '上传失败'))
      message.error('头像上传失败')
    }
  } catch (error) {
    console.error('头像上传失败:', error)
    onError(error)
    message.error('头像上传失败')
  } finally {
    avatarUploading.value = false
  }
}

/**
 * 头像上传状态变化
 */
const handleAvatarChange = (info) => {
  if (info.file.status === 'uploading') {
    avatarUploading.value = true
    return
  }

  if (info.file.status === 'done') {
    avatarUploading.value = false
    // 文件上传成功，头像URL已在customAvatarUpload中设置
  }

  if (info.file.status === 'error') {
    avatarUploading.value = false
    message.error('头像上传失败')
  }
}

/**
 * 删除头像
 */
const handleAvatarRemove = () => {
  editForm.avatar = ''
  return true
}

/**
 * 选择咖啡杯类型
 */
const selectCoffeeType = (typeIndex) => {
  editForm.typeIndex = typeIndex
}

function showCupTip(event, cup, index) {
  hoveredIndex.value = index
  cupTip.text = cup.hasAvatar ? cup.name || '匿名支持者' : '空座位'
  cupTip.visible = true
  moveCupTip(event)
}
function moveCupTip(event) {
  if (!cupTip.visible) return
  cupTip.style.left = event.clientX + 16 + 'px'
  cupTip.style.top = event.clientY + 16 + 'px'
}
function hideCupTip() {
  hoveredIndex.value = -1
  cupTip.visible = false
}
</script>

<style>
/* 全局样式确保modal样式生效 */
.certificate-modal .ant-modal-content {
  background: transparent !important;
  box-shadow: none !important;
}
</style>

<style scoped>
.coffee-wall {
  height: 100vh;
  background-image: url('@/assets/wall.jpg');
  padding: 20px;
  position: relative;
  overflow-y: auto;
}

.wall-header {
  text-align: center;
  margin-bottom: 40px;
  position: relative;
  z-index: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}

.wall-title {
  font-size: 3rem;
  color: #f4e4bc;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
  font-weight: bold;
}

.wall-subtitle {
  font-size: 1.2rem;
  color: #d4af37;
  margin-bottom: 0;
  opacity: 0.9;
  margin-right: 30px;
}

.wall-stats {
  display: flex;
  justify-content: center;
  gap: 40px;
  margin-top: 20px;
}

.stat-item {
  text-align: center;
}

.stat-number {
  display: block;
  font-size: 2rem;
  font-weight: bold;
  color: #d4af37;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
}

.stat-label {
  display: block;
  font-size: 0.9rem;
  color: #f4e4bc;
  opacity: 0.8;
  margin-top: 5px;
}

.coffee-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
  width: 86%;
  min-width: 760px;
  margin: 0 auto;
  position: relative;
  z-index: 5;
  background-image: url('@/assets/glass.svg');
  background-repeat: repeat-y;
  background-position: center top;
  background-attachment: local;
}

.coffee-cup {
  aspect-ratio: 1;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  border-radius: 10px;
  overflow: hidden;
  z-index: 10;
}

.coffee-cup.has-avatar {
  z-index: 20;
}

.coffee-cup.is-empty {
  z-index: 5;
  filter: brightness(0.4) contrast(1.1);
  transform: translateY(5px);
  transition: filter 0.1s ease, transform 0.1s ease;
}

.coffee-cup.is-empty:hover {
  filter: none;
  transform: translateY(0);
}

.cup-background {
  width: 100%;
  height: 100%;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-container {
  position: absolute;
  top: 61%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 64px;
  height: 64px;
  border-radius: 50%;
  overflow: hidden;
  border: 2px solid #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
}

.coffee-cup:hover .avatar-container {
  top: 56%;
  width: 74px;
  height: 74px;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.empty-seat-hint {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  color: #000000;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.coffee-cup.is-empty:hover .empty-seat-hint {
  opacity: 1;
}

.plus-icon {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 4px;
}

.hint-text {
  font-size: 10px;
  white-space: nowrap;
}

.action-section {
  text-align: center;
  margin: 40px 0;
  position: relative;
  z-index: 1;
}

.sponsor-btn {
  height: 50px;
  padding: 0 30px;
  font-size: 1.1rem;
  background: linear-gradient(135deg, #d4af37 0%, #f4e4bc 100%);
  border: none;
  color: #2c1810;
  font-weight: bold;
}

.sponsor-btn:hover {
  background: linear-gradient(135deg, #f4e4bc 0%, #d4af37 100%);
}

.action-description {
  color: #f4e4bc;
  margin-top: 15px;
  opacity: 0.8;
}

.certificate-container {
  position: relative;
  background: #1a1a2e;
  border-radius: 20px;
  overflow: hidden;
  padding: 140px 10px;
  color: #fff;
}

.flower-border-bg {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image: url('@/assets/flower-border.png');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  opacity: 0.3;
}

.certificate-content {
  position: relative;
  z-index: 1;
  text-align: center;
}

.certificate-header {
  margin-bottom: 20px;
}

.certificate-title {
  color: #90ee90;
  font-size: 2rem;
  font-weight: bold;
  margin: 0 0 10px 0;
  text-shadow: 0 0 10px rgba(144, 238, 144, 0.5);
}

.certificate-subtitle {
  color: #90ee90;
  font-size: 1rem;
  margin: 0;
  opacity: 0.9;
}

.certificate-cup {
  position: relative;
  display: inline-block;
  margin: 20px 0;
}

.cup-image {
  width: 140px;
  height: 140px;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cup-img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.cert-avatar {
  position: absolute;
  top: 62.5%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 52px;
  height: 52px;
  border-radius: 50%;
  border: 2px solid #fff;
  z-index: 5;
  object-fit: cover;
}

.cup-badge {
  position: absolute;
  bottom: -5px;
  right: -5px;
  background: #90ee90;
  color: #1a1a2e;
  font-size: 12px;
  font-weight: bold;
  padding: 4px 8px;
  border-radius: 12px;
  border: 2px solid #1a1a2e;
}

.supporter-name {
  color: #90ee90;
  font-size: 1.5rem;
  font-weight: bold;
  margin: 15px 0;
}

.certificate-info {
  margin: 20px 0;
}

.support-message {
  color: #fff;
  font-style: italic;
  line-height: 1.6;
  margin: 15px 0;
  opacity: 0.9;
}

.support-date {
  color: #90ee90;
  font-size: 0.8rem;
  margin: 10px 0;
}

.certificate-actions {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 20px;
  position: relative;
  z-index: 1;
}

.cert-btn {
  border-radius: 25px;
  height: 40px;
  padding: 0 25px;
  font-weight: bold;
  border: 2px solid #90ee90;
}

.cert-btn-download {
  background: transparent;
  color: #90ee90;
}

.cert-btn-download:hover {
  background: #90ee90;
  color: #1a1a2e;
}

.cert-btn-support {
  background: #90ee90;
  border-color: #90ee90;
  color: #1a1a2e;
}

.cert-btn-support:hover {
  background: #7ccd7c;
  border-color: #7ccd7c;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .wall-title {
    font-size: 2rem;
  }

  .wall-subtitle {
    font-size: 1rem;
  }

  .wall-stats {
    gap: 20px;
  }

  .stat-number {
    font-size: 1.5rem;
  }

  .avatar-container {
    width: 74px;
    height: 74px;
  }

  .certificate-container {
    padding: 20px;
  }

  .certificate-title {
    font-size: 1.5rem;
  }

  .cup-image {
    width: 80px;
    height: 80px;
  }

  .cup-img {
    width: 100%;
    height: 100%;
  }
}

@media (max-width: 480px) {
  .wall-title {
    font-size: 1.5rem;
  }

  .wall-stats {
    flex-direction: column;
    gap: 15px;
  }

  .sponsor-btn {
    height: 45px;
    font-size: 1rem;
  }
}

.admin-controls {
  display: flex;
  justify-content: center;
}

.admin-toggle-btn,
.admin-add-btn {
  height: 40px;
  padding: 0 20px;
  font-weight: bold;
  border-radius: 20px;
}

.admin-actions {
  position: absolute;
  top: 5px;
  right: 5px;
  display: flex;
  gap: 5px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.coffee-cup:hover .admin-actions {
  opacity: 1;
}

.action-btn {
  width: 24px;
  height: 24px;
  padding: 0;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.edit-btn {
  background: #52c41a;
  border-color: #52c41a;
}

.delete-btn {
  background: #ff4d4f;
  border-color: #ff4d4f;
}

/* 编辑弹窗样式 */
.edit-supporter-modal .ant-modal-body {
  padding: 20px;
}

.edit-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-label {
  font-weight: bold;
  color: #333;
  font-size: 14px;
}

.form-label .required {
  color: #ff4d4f;
  margin-left: 4px;
}

.form-input {
  width: 100%;
}

/* 头像上传样式 */
.avatar-uploader {
  width: 100%;
}

.avatar-uploader .ant-upload {
  width: 120px;
  height: 120px;
  border-radius: 8px;
  border: 1px dashed #d9d9d9;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: border-color 0.3s;
}

.avatar-uploader .ant-upload:hover {
  border-color: #1890ff;
}

.avatar-preview {
  position: relative;
  width: 100%;
  height: 100%;
  border-radius: 8px;
  overflow: hidden;
}

.avatar-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.avatar-preview:hover .avatar-overlay {
  opacity: 1;
}

.avatar-actions {
  display: flex;
  gap: 8px;
}

.remove-btn {
  color: white !important;
  background: rgba(255, 77, 79, 0.8) !important;
  border: none !important;
  border-radius: 4px !important;
  padding: 4px 8px !important;
}

.remove-btn:hover {
  background: rgba(255, 77, 79, 1) !important;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #666;
  font-size: 14px;
}

.upload-placeholder .anticon {
  font-size: 24px;
  margin-bottom: 8px;
}

.upload-text {
  font-size: 12px;
}

/* 咖啡杯类型选择样式 */
.coffee-type-selector {
  width: 100%;
  display: flex;
  justify-content: space-between;
  gap: 15px;
}

.coffee-option {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 15px;
  border: 2px solid #e8e8e8;
  border-radius: 16px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  cursor: pointer;
  background: linear-gradient(145deg, #ffffff, #f8f9fa);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  position: relative;
  overflow: hidden;
}

.coffee-option::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(145deg, rgba(255, 255, 255, 0.8), rgba(248, 249, 250, 0.8));
  opacity: 0;
  transition: opacity 0.3s ease;
}

.coffee-option.active {
  border-color: #d4af37;
  background: linear-gradient(145deg, #fff9e6, #f4e4bc);
  box-shadow: 0 8px 24px rgba(212, 175, 55, 0.3);
}

.coffee-option.active::after {
  content: '✓';
  position: absolute;
  top: 8px;
  right: 8px;
  width: 20px;
  height: 20px;
  background: #d4af37;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: bold;
}

.coffee-preview {
  width: 60px;
  height: 60px;
  object-fit: contain;
  margin-bottom: 12px;
  filter: drop-shadow(0 2px 8px rgba(0, 0, 0, 0.1));
  transition: transform 0.3s ease;
}

.coffee-label {
  font-size: 14px;
  color: #4a4a4a;
  text-align: center;
  font-weight: 600;
  letter-spacing: 0.5px;
}

.coffee-option.active .coffee-label {
  color: #d4af37;
  font-weight: 700;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .coffee-type-selector {
    flex-direction: column;
    gap: 12px;
  }

  .coffee-option {
    padding: 15px 12px;
  }

  .coffee-preview {
    width: 50px;
    height: 50px;
  }

  .coffee-label {
    font-size: 13px;
  }
}

/* 响应式管理功能 */
@media (max-width: 768px) {
  .admin-controls {
    flex-direction: column;
    gap: 10px;
  }

  .admin-toggle-btn,
  .admin-add-btn {
    height: 36px;
    font-size: 14px;
  }

  .admin-actions {
    top: 3px;
    right: 3px;
    gap: 3px;
  }

  .action-btn {
    width: 20px;
    height: 20px;
  }
}

.cup-tip {
  position: fixed;
  background: rgba(0, 0, 0, 0.85);
  color: #fff;
  padding: 6px 16px;
  border-radius: 6px;
  font-size: 14px;
  pointer-events: none;
  white-space: nowrap;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  z-index: 9999;
  transition: opacity 0.15s;
  opacity: 1;
  max-width: 220px;
  text-overflow: ellipsis;
  overflow: hidden;
}
</style>
